'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
// const uniAccount = require('uni-account');

var axios = require('axios')

'use strict';
module.exports = {
	/**
	 * 此函数名称
	 * @url client/order/kh/test 前端调用的url参数地址
	 * data 请求参数
	 * @params {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, originalParam } = event;
		let { customUtil, config, pubFun, vk, db, _,uniID } = util;
		let { uid } = data;
		var res = { code : 0, msg : '' };
		// 业务逻辑开始-----------------------------------------------------------
		// 可写与数据库的交互逻辑等等
		var appIds
		var appSecrets
		console.log(data.mptype,'asdfasdfasdfasdfasd')
		if(data.mptype == 'wx'){
			appIds = await db.collection('wx_config').where({'key': 'wxIdApp'}).get()
			appSecrets = await db.collection('wx_config').where({'key': 'wxSecretApp'}).get()
		}else if(data.mptype == 'qq'){
			appIds = await db.collection('wx_config').where({'key': 'qqId'}).get()
			appSecrets = await db.collection('wx_config').where({'key': 'qqSecret'}).get()
		}else if(data.mptype == 'toutiao'){
			if(data.appSecret && data.appId){
				// 多个小程序
				appIds = {data:[{val:data.appId}]}
				appSecrets = {data:[{val:data.appSecret}]}
			}else{
				// 单个小程序
				appIds = await db.collection('wx_config').where({'key': 'toutiaoId'}).get()
				appSecrets = await db.collection('wx_config').where({'key': 'toutiaoSecret'}).get()
			}
			
			
		}
		if(data.mptype == 'wx' || data.mptype == 'qq' ||  data.mptype == 'toutiao' ){
			if (appIds.data.length === 0 || appSecrets.data.length === 0) {
				return {
					success: false,
					msg: '未配置登录参数'
				}
			}
			const appId = appIds.data[0].val
			const appSecret = appSecrets.data[0].val
			if (!appId || !appSecret) {
				return {
					success: false,
					msg: '登录需要配置appid和密钥'
				}
			}
			// 配置登录参数
			// var uniAccountIns = uniAccount.initWeixin({
			// 	appId: appId,
			// 	secret: appSecret
			// })
			// if(data.mptype === 'qq'){
			// 	uniAccountIns = uniAccount.initQQ({
			// 		appId: appId,
			// 		secret: appSecret
			// 	})
			// }
		}
		
		
		if(data.mptype === 'app_wx' || data.mptype === 'app_email' || data.mptype === 'h5' || data.mptype == 'app_phone'){
			var res = {}
		}else if(data.mptype === 'wx' || data.mptype == 'qq') {
			var res = await uniAccountIns.code2Session(data.code);
		}else if(data.mptype == 'toutiao'){
			const appId = appIds.data[0].val
			const appSecret = appSecrets.data[0].val
			if (!appId || !appSecret) {
				return {
					success: false,
					msg: '登录需要配置appid和密钥'
				}
			}
			try{
				var resData = await axios.post('https://developer.toutiao.com/api/apps/v2/jscode2session', {
					"appid": appId,
					"secret": appSecret,
					"code": data.code,
					"anonymous_code": data.anonymousCode
				})
				console.log(resData,'resDataresDataresDataresDataresData')
				var res = resData.data.data
				
				
			}catch(e){
				console.log(e,'11111111111111')
				//TODO handle the exception
			}
			
			
		}
		let timeStamp = new Date().getTime()
		var newdate = {};
		var wx_user = await db.collection('uni-id-users').where({openid:data.openid || res.openid}).get();
		// 判断用户是否存在
		if (wx_user.data.length == 0) {
			let tempOpenId = data.openid || res.openid
			newdate = {
				openid:tempOpenId,
				"wx_openid": {
				    "toutiao": tempOpenId
				},
				"my_invite_code": "",
				"register_env": {
				},
				"dcloud_appid": [
				],
				"register_date": new Date().getTime(),
				"token": [],
				"avatar": data.avatar || "/static/default.jpg",
				"nickname": data.name || '昵称_' + tempOpenId.slice(tempOpenId.length - 4),
				"status": 0,
				"last_login_date": '',
				"last_login_ip": "",
				mp: data.mptype || '',
				
			};
		
			let user_new = await db.collection('uni-id-users').add(newdate);
			let resToken =  await uniID.createToken({
				uid:user_new.id
			})
			await db.collection('uni-id-users').where({openid:data.openid || res.openid}).update({
				token:[resToken.token],
				last_login_date:resToken.tokenExpired
			})
		
		} else {
			if( data.mptype === 'app_email' || data.mptype === 'h5' || data.mptype == 'app_phone'){
				return {
					success: false,
					msg: '此邮箱已经注册了，不能再次注册'
				}
			}
			let resToken =  await uniID.createToken({
				uid:wx_user.data[0]._id
			})
			let tokens = [...wx_user.data[0].token,resToken.token]
			var user_update = await db.collection('uni-id-users').where({openid:data.openid || res.openid}).update({
				token:tokens,
				last_login_date:resToken.tokenExpired
			})
		}
		
		// 查询最新的数据
		var result = await db.collection('uni-id-users').where({openid:data.openid || res.openid}).get();
		if (result.data.length > 0) {
		
			
			delete result.data[0].record
				return {
					 code : 0, 
					 msg : "查询成功" ,
					 data: result.data[0],
					 token:{
						 token:result.data[0].token[result.data[0].token.length - 1],
						 tokenExpired:result.data[0].last_login_date
					 }
				}
			// return {
			// 	success: true,
			// 	data: result.data[0]
			// }
		} else {
			return {
				code : -1,
				msg: '用户不存在'
			}
		}



		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}




// exports.main = async (event, context) => {
// 	if (event.queryStringParameters) {
// 		event = {
// 			...event,
// 			...event.queryStringParameters
// 		}
// 	}

// 	var appIds
// 	var appSecrets
// 	if(event.mptype == 'wx'){
// 		appIds = await db.collection('wx_config').where({'key': 'wxId'}).get()
// 		appSecrets = await db.collection('wx_config').where({'key': 'wxSecret'}).get()
// 	}else if(event.mptype == 'qq'){
// 		appIds = await db.collection('wx_config').where({'key': 'qqId'}).get()
// 		appSecrets = await db.collection('wx_config').where({'key': 'qqSecret'}).get()
// 	}else if(event.mptype == 'toutiao'){
// 		appIds = await db.collection('wx_config').where({'key': 'toutiaoId'}).get()
// 		appSecrets = await db.collection('wx_config').where({'key': 'toutiaoSecret'}).get()
// 	}
// 	if(event.mptype == 'wx' || event.mptype == 'qq' ||  event.mptype == 'toutiao' ){
// 		if (appIds.data.length === 0 || appSecrets.data.length === 0) {
// 			return {
// 				success: false,
// 				msg: '未配置登录参数'
// 			}
// 		}
// 		const appId = appIds.data[0].val
// 		const appSecret = appSecrets.data[0].val
// 		if (!appId || !appSecret) {
// 			return {
// 				success: false,
// 				msg: '登录需要配置appid和密钥'
// 			}
// 		}
// 		// 配置登录参数
// 		var uniAccountIns = uniAccount.initWeixin({
// 			appId: appId,
// 			secret: appSecret
// 		})
// 		if(event.mptype === 'qq'){
// 			uniAccountIns = uniAccount.initQQ({
// 				appId: appId,
// 				secret: appSecret
// 			})
// 		}
// 	}


// 	if(event.mptype === 'app_wx' || event.mptype === 'app_email' || event.mptype === 'h5' || event.mptype == 'app_phone'){
// 		var res = {}
// 	}else if(event.mptype === 'wx' || event.mptype == 'qq') {
// 		var res = await uniAccountIns.code2Session(event.code);
// 	}else if(event.mptype == 'toutiao'){
// 		const appId = appIds.data[0].val
// 		const appSecret = appSecrets.data[0].val
// 		if (!appId || !appSecret) {
// 			return {
// 				success: false,
// 				msg: '登录需要配置appid和密钥'
// 			}
// 		}
// 		try{
// 			var resData = await axios.post('https://developer.toutiao.com/api/apps/v2/jscode2session', {
// 				"appid": appId,
// 				"secret": appSecret,
// 				"code": event.code,
// 				"anonymous_code": event.anonymousCode
// 			})
// 			var res = resData.data.data
// 		}catch(e){
// 			//TODO handle the exception
// 		}
		
		
// 	}
// 	let timeStamp = new Date().getTime()
// 	var newdate = {};
// 	var wx_user = await db.collection('wx_user').where({openid:event.openId || res.openid}).get();
// 	// 判断用户是否存在
// 	if (wx_user.data.length == 0) {
// 		newdate = {
// 			openid:event.openId || res.openid,
// 			password:event.password,
// 			name: event.name,
// 			avatar: event.avatar,
// 			integral: 0,
// 			status: 1,
// 			mp: event.mptype,
// 			time: timeStamp,
// 			dis_grade:1,
// 			money:0
// 		};
// 		var user_new = await db.collection('wx_user').add(newdate);

// 	} else {
// 		if( event.mptype === 'app_email' || event.mptype === 'h5' || event.mptype == 'app_phone'){
// 			return {
// 				success: false,
// 				msg: '此邮箱已经注册了，不能再次注册'
// 			}
// 		}
// 		var user_update = await db.collection('wx_user').where({openid:event.openId || res.openid}).update({
// 			"wx_openid":res.openid || '',
// 			// 'name': event.name,
// 			// 'avatar': event.avatar
// 		})
// 	}

// 	// 查询最新的数据
// 	var result = await db.collection('wx_user').where({openid:event.openId || res.openid}).get();
// 	if (result.data.length > 0) {
// 		delete result.data[0].record
// 		return {
// 			success: true,
// 			data: result.data[0]
// 		}
// 	} else {
// 		return {
// 			success: false,
// 			msg: '用户不存在'
// 		}
// 	}
// };
